package com.shopping.dev.service.impl;

import com.shopping.dev.bo.UserBO;
import com.shopping.dev.common.enums.SexEnum;
import com.shopping.dev.common.util.DateUtil;
import com.shopping.dev.common.util.IdUtil;
import com.shopping.dev.common.util.Md5Util;
import com.shopping.dev.mapper.UsersMapper;
import com.shopping.dev.pojo.Users;
import com.shopping.dev.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UsersMapper usersMapper;
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean existUserName(String userName) {
        Example userExample = new Example(Users.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andEqualTo("username",userName);
        Users users = usersMapper.selectOneByExample(userExample);
        return users == null ? true : false;
    }
    @Transactional(propagation = Propagation.REQUIRED )
    @Override
    public Users regist(UserBO user) {
        Users u = new Users();
        String uuid = IdUtil.getUUID();
        u.setId(uuid);
        u.setUsername(user.getUsername());
        u.setPassword(Md5Util.getMD5Str(user.getPassword()));
        u.setBirthday(DateUtil.stringToDate("1970-01-01",null));
        u.setNickname(user.getNickname());
        u.setSex(SexEnum.SECRET.getCode());
        u.setCreatedTime(new Date());
        u.setUpdatedTime(new Date());
        int insert = usersMapper.insert(u);
        return insert == 0 ? null : u;
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public UserBO selectUser(String userName, String passwd) {
        Example userExample = new Example(Users.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andEqualTo("username",userName);
        userCriteria.andEqualTo("password",Md5Util.getMD5Str(passwd));
        Users users = usersMapper.selectOneByExample(userExample);
        UserBO userBO = new UserBO();
        if (users!=null){
            BeanUtils.copyProperties(users,userBO);
            return userBO;
        }
        return null;
    }


}
